package retrospection.括号生成;

import java.util.ArrayList;
import java.util.List;

public class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> ans = new ArrayList<>();
        backtrack(n, ans, 0, 0, new StringBuilder());
        return ans;
    }

    void backtrack(int n, List<String> ans, int open, int close, StringBuilder sb) {
        if (open == n && close == n) {
            ans.add(sb.toString());
            return;
        }

        if (open < n) {
            sb.append('(');
            backtrack(n, ans, open + 1, close, sb);
            sb.deleteCharAt(sb.length() - 1);
        }

        if (close < open) {
            sb.append(')');
            backtrack(n, ans, open, close + 1, sb);
            sb.deleteCharAt(sb.length() - 1);
        }
    }

    public static void main(String[] args) {
        System.out.println(new Solution().generateParenthesis(3));
    }
}
